﻿#region *** Imports ***
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Design;
using System.Globalization;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net;
using System.Configuration;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Drawing.Imaging;
using ColorProgressBar;
using SpPerfChart;
using System.Media;
#endregion

namespace RadLogger_Pro {
    public partial class Main : Form
    {
        #region *** Setting standard parameters ***
        //[DllImport("user32.dll")]
        private Dictionary<string, MemoryStream> dict = new Dictionary<string, MemoryStream>();
        private double conversionFactor = Properties.Settings.Default.ConversionFactor;
        private double absorbed = 0;
        private double oneMinuteAverage = 0;
        private double confRateConf = Properties.Settings.Default.ConversionFactor;
        //private static extern bool FlashWindow(IntPtr hwnd, bool bInvert);
        private bool saveToLogBool = false;
        private bool connectToRadMon = false;
        private bool close = false;
        private bool alarmOn = Properties.Settings.Default.alarmOn;
        private bool ftpUpload = false;
        private int alarmThreshold = Properties.Settings.Default.AlertThreshold;
        private int warningThreshold = Properties.Settings.Default.WarningThreshold;
        private int SecondsLeft = 60;
        private int FtpSecondsLeft = 300;
        private int cpmParsedInt = 0;
        private int intToUpload;
        private List<string> logBuffer = new List<string>();
        private List<int> oneMinuteCMPList = new List<int>();
        private SerialPort comPort;
        private SoundPlayer player = new SoundPlayer();
        private string logFilePath;
        private string settingsFilePath = Application.StartupPath + @"\Config\Settings.config";
        private string cpmReceivedString = string.Empty;
        private StringBuilder itemToAdd = new StringBuilder();
        private Thread _ftp;
        private Thread _rad;
        private Thread case1;
        private Thread case3;
        #endregion

        public Main()
        {
            InitializeComponent();
        }

        #region *** Main loading event ***
        private void Main_Load(object sender, EventArgs e)
        {
            player.Stream = Properties.Resources.RadAlarm;
            // Create directorys if they do not exist already
            if (!Directory.Exists(Application.StartupPath + @"\Logs"))
            {
                Directory.CreateDirectory(Application.StartupPath + @"\Logs");
            }

            if (!Directory.Exists(Application.StartupPath + @"\ChartImages"))
            {
                Directory.CreateDirectory(Application.StartupPath + @"\ChartImages");
            }

            if (Properties.Settings.Default.alarmOn == true)
            {
                alarmOnToolStripMenuItem.Text = "\u2714 Alarm on";
            }
            else
            {
                alarmOnToolStripMenuItem.Text = "Alarm on";
            }

            if (Properties.Settings.Default.colorSetting == "Dark")
            {
                darkToolStripMenuItem.Text = "\u2714 Dark";
                lightToolStripMenuItem.Text = "Light";
                colorDark();
            }
            else if (Properties.Settings.Default.colorSetting == "Light")
            {
                darkToolStripMenuItem.Text = "Dark";
                lightToolStripMenuItem.Text = "\u2714 Light";
                colorLight();
            }
            else
            {
                darkToolStripMenuItem.Text = "\u2714 Dark";
                lightToolStripMenuItem.Text = "Light";
                colorDark();
            }

            if (Properties.Settings.Default.CalcMethod == "S")
            {
                useΜSvToolStripMenuItem.Text = "\u2714 Use µSv";
                useΜRToolStripMenuItem.Text = "Use µR";
            }
            else if (Properties.Settings.Default.CalcMethod == "R")
            {
                useΜSvToolStripMenuItem.Text = "Use µSv";
                useΜRToolStripMenuItem.Text = "\u2714 Use µR";
            }
            else
            {
                Properties.Settings.Default.CalcMethod = "S";
                Properties.Settings.Default.Save();
                useΜSvToolStripMenuItem.Text = "\u2714 Use µSv";
                useΜRToolStripMenuItem.Text = "Use µR";
            }

            labelCpm.ForeColor = Color.Black;
            conversionFactorLabel.Text = Convert.ToString(Properties.Settings.Default.ConversionFactor);
            toolTips.SetToolTip(SaveLogToFileCheckbox, "Logs will be saved to \r\n" + Path.GetDirectoryName(Application.ExecutablePath) + @"\Log\");
            AlertThresholdLabel.Text = Properties.Settings.Default.AlertThreshold.ToString(CultureInfo.InvariantCulture);
            WarningThresholdLabel.Text = Properties.Settings.Default.WarningThreshold.ToString(CultureInfo.InvariantCulture);
            TrayIcon.ContextMenuStrip = trayMenuStrip;
            colorProgressBar1.Minimum = 0;
            colorProgressBar1.Maximum = 100;
            colorProgressBar1.Step = 1;
            colorProgressBar1.Value = 0;
            perfChart1.TimerInterval = 60000;
            labelIndiMax.Text = "Indicator maximum value: " + colorProgressBar1.Maximum.ToString();
            labelCpm.Text = "Off";

            if (Properties.Settings.Default.CalcMethod == "S")
            {
                currentRadiationLevelLabel.Text = "0.0000 µSv/h";
                AbsorbedValueLabel.Text = "0.0000 µSv";
            }
            else if (Properties.Settings.Default.CalcMethod == "R")
            {
                currentRadiationLevelLabel.Text = "0.0000 µR/h";
                AbsorbedValueLabel.Text = "0.0000 µR";
            }
        }
        #endregion

        #region *** Conversion factor save button event ***
        private void conversionFactorSaveButton_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.ConversionFactor = Convert.ToDouble(conversionFactorLabel.Text);
            Properties.Settings.Default.Save();

        }
        #endregion

        #region *** Alert theshold save button event ***
        private void AlertThresholdSaveButton_Click(object sender, EventArgs e)
        {
            int parsedThreshold;
            if (int.TryParse(AlertThresholdLabel.Text, out parsedThreshold) == true)
            {
                int convertedThreshold = Convert.ToInt32(AlertThresholdLabel.Text);
                Properties.Settings.Default.AlertThreshold = convertedThreshold;
                Properties.Settings.Default.Save();
            }
            else
            {
                MessageBox.Show("Please enter integer threshold number before saving!");
            }
        }
        #endregion

        #region *** Warning threshold save button event ***
        private void WarningThresholdSaveButton_Click(object sender, EventArgs e)
        {
            int convertedWarningThreshold = Convert.ToInt32(WarningThresholdLabel.Text);
            Properties.Settings.Default.WarningThreshold = convertedWarningThreshold;
            Properties.Settings.Default.Save();
        }
        #endregion

        #region *** Uploading to RadMon event ***
        private void uploadToRadMon(object sender, EventArgs e)
        {
            oneMinuteAverage = 0;
            intToUpload = 0;

            if (Properties.Settings.Default.LoggerMode == 2)
            {
                lock (oneMinuteCMPList)
                {
                    try
                    {
                        oneMinuteAverage = ((int)oneMinuteCMPList.Average()) * Properties.Settings.Default.ConversionFactor;
                        intToUpload = ((int)oneMinuteCMPList.Average());
                        absorbed = absorbed + (oneMinuteAverage / 60);
                    }
                    catch (Exception) { }
                }

                double absorbedMicroSievert = Math.Round(absorbed, 4, MidpointRounding.AwayFromZero);
                AbsorbedValueLabel.Text = absorbedMicroSievert.ToString(CultureInfo.InvariantCulture) + " µSv";

                // Maximum value switches
                if (intToUpload < 100)
                {
                    colorProgressBar2.Maximum = 100;
                }
                else if (intToUpload < 1000)
                {
                    colorProgressBar2.Maximum = 1000;
                }
                else if (intToUpload < 5000)
                {
                    colorProgressBar2.Maximum = 5000;
                }
                else if (intToUpload < 10000)
                {
                    colorProgressBar2.Maximum = 10000;
                }
                else if (intToUpload < 15000)
                {
                    colorProgressBar2.Maximum = 15000;
                }
                else
                {
                    colorProgressBar2.Maximum = 100000;
                }

                colorProgressBar2.Value = intToUpload;

                //// Create a request using a URL that can receive a post. 
                //WebRequest request = WebRequest.Create(
                //    "http://www.radmon.org/radmon.php?user=" +
                //    Properties.Settings.Default.RadMonUserName +
                //    "&password=" + Properties.Settings.Default.RadMonUserPassword +
                //    "&function=submit&datetime=" + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") +
                //    "&value=" + intToUpload + "&unit=CPM");
                //request.Timeout = 15000;
                //Application.DoEvents();

                //// Get the response.
                //try
                //{
                //    WebResponse response;
                //    using (response = request.GetResponse()) { }
                //}
                //catch (Exception ex)
                //{
                //    MessageBox.Show("Error submitting value : " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //}

                _rad = new Thread(new ThreadStart(_radUpload));
                _rad.Start();

                lock (oneMinuteCMPList)
                {
                    oneMinuteCMPList.Clear();
                }

                toolStripStatusLabelUploaded.Text = "Last upload: " + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " local time.";
            }
            else
            {

                lock (oneMinuteCMPList)
                {
                    try
                    {
                        oneMinuteAverage = (int)oneMinuteCMPList.Average() * Properties.Settings.Default.ConversionFactor;
                        intToUpload = (int)oneMinuteCMPList.Average();
                        absorbed = absorbed + oneMinuteAverage / 60;
                    }
                    catch (Exception) { }
                }

                double absorbedMicroSievert = Math.Round(absorbed, 4, MidpointRounding.AwayFromZero);
                AbsorbedValueLabel.Text = absorbedMicroSievert.ToString(CultureInfo.InvariantCulture) + " µSv";

                // Maximum value switches
                if (intToUpload < 100)
                {
                    colorProgressBar2.Maximum = 100;
                }
                else if (intToUpload < 1000)
                {
                    colorProgressBar2.Maximum = 1000;
                }
                else if (intToUpload < 5000)
                {
                    colorProgressBar2.Maximum = 5000;
                }
                else if (intToUpload < 10000)
                {
                    colorProgressBar2.Maximum = 10000;
                }
                else if (intToUpload < 15000)
                {
                    colorProgressBar2.Maximum = 15000;
                }
                else
                {
                    colorProgressBar2.Maximum = 100000;
                }

                colorProgressBar2.Value = intToUpload;

                _rad = new Thread(new ThreadStart(_radUpload));
                _rad.Start();

                lock (oneMinuteCMPList)
                {
                    oneMinuteCMPList.Clear();
                }

                toolStripStatusLabelUploaded.Text = "Last upload: " + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " local time.";
            }
        }
        #endregion

        #region *** Upload to FTP server ***
        private void UploadFileToFTP()
        {
            //try
            //{
            //    using (var png = new Bitmap(perfChart1.Width, perfChart1.Height))
            //    {
            //        perfChart1.DrawToBitmap(png, new Rectangle(0, 0, png.Width, png.Height));
            //        FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://" + Properties.Settings.Default.ftpUrl + "/" + Properties.Settings.Default.ftpFileName + ".png");
            //        request.Method = WebRequestMethods.Ftp.UploadFile;
            //        request.Credentials = new NetworkCredential(Properties.Settings.Default.ftpUser, Properties.Settings.Default.ftpPass);
            //        request.UseBinary = true;
            //        png.Save(request.GetRequestStream(), ImageFormat.Png);
            //        Application.DoEvents();
            //        png.Dispose();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("Error uploading the graph to the FTP server!\r\n" + ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
            try
            {
                using (var png = new Bitmap(perfChart1.Width, perfChart1.Height))
                {
                    perfChart1.DrawToBitmap(png, new Rectangle(0, 0, png.Width, png.Height));

                    WebRequest reqObj = WebRequest.Create("ftp://" + Properties.Settings.Default.ftpUrl + "/" + Properties.Settings.Default.ftpFileName + ".png");
                    FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create("ftp://" + Properties.Settings.Default.ftpUrl + "/" + Properties.Settings.Default.ftpFileName + ".png");

                    ftpClient.Credentials = new System.Net.NetworkCredential(Properties.Settings.Default.ftpUser, Properties.Settings.Default.ftpPass);
                    ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
                    ftpClient.UseBinary = true;
                    ftpClient.KeepAlive = true;
                    ftpClient.ContentLength = png.PropertyItems.Length;

                    Stream rs = ftpClient.GetRequestStream();
                    png.Save(rs, ImageFormat.Png);

                    rs.Close();
                    png.Dispose();

                    FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();

                    uploadResponse.Close();
                }

                Application.DoEvents();
            }
            catch (Exception Ex)
            {
                MessageBox.Show("Error saving the chart." + Ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            _ftp.Abort();
        }
        #endregion

        #region *** Seconds left event ***
        private void secsLeft(object sender, EventArgs e)
        {
            if (SecondsLeft <= 1)
            {
                SecondsLeft = 60;
                labelTimeLeft.Text = "Time left untill next upload: " + Convert.ToString(SecondsLeft);
            }
            else if (SecondsLeft > 1)
            {
                SecondsLeft = SecondsLeft - 1;
                labelTimeLeft.Text = "Time left untill next upload: " + Convert.ToString(SecondsLeft);
            }

            if (FtpSecondsLeft <= 1)
            {
                FtpSecondsLeft = 300;
                labelFTPTimeLeft.Text = "Time left untill next FTP upload: " + Convert.ToString(FtpSecondsLeft);
            }
            else if (FtpSecondsLeft > 1)
            {
                FtpSecondsLeft = FtpSecondsLeft - 1;
                labelFTPTimeLeft.Text = "Time left untill next FTP upload: " + Convert.ToString(FtpSecondsLeft);
            }
        }
        #endregion

        #region *** Start button click event ***
        private void startLogButton_Click(object sender, EventArgs e)
        {
            absorbed = 0;
            alarmThreshold = Convert.ToInt32(AlertThresholdLabel.Text);

            if (SaveLogToFileCheckbox.Checked == true)
            {
                saveToLogBool = true;
                logFilePath = Application.StartupPath + @"\Logs\Radiation log-" + DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss", CultureInfo.InvariantCulture) + @".csv";
            }
            else if (SaveLogToFileCheckbox.Checked == false)
            {
                saveToLogBool = false;
            }
            else
            {
                saveToLogBool = false;
            }

            if (checkBoxConRadMon.Checked == true)
            {
                connectToRadMon = true;
            }
            else if (checkBoxConRadMon.Checked == false)
            {
                connectToRadMon = false;
            }
            else
            {
                connectToRadMon = false;
            }

            if (checkBoxFtpUpload.Checked == true)
            {
                ftpUpload = true;
            }
            else if (checkBoxFtpUpload.Checked == false)
            {
                ftpUpload = false;
            }
            else
            {
                ftpUpload = false;
            }

            if (Properties.Settings.Default.PortString == "")
            {
                MessageBox.Show("Please configure the settings\n\rneeded to connect to your kit.");
                return;
            }
            else { }

            if (double.TryParse(conversionFactorLabel.Text, out conversionFactor) == false)
            {
                MessageBox.Show("Please set Conversion Factor (try comma instead of dot)");
                return;
            }
            else { }

            if (startLogButton.Text == "Start Logging")
            {
                labelCpm.ForeColor = Color.DarkGreen;
                colorProgressBar1.BarColor = Color.DarkGreen;
                colorProgressBar1.Minimum = 0;
                colorProgressBar1.Maximum = 100;
                colorProgressBar1.Step = 1;
                colorProgressBar1.Value = 0;
                cpmParsedInt = 0;
                labelIndiMax.Text = "Indicator maximum value: " + colorProgressBar1.Maximum.ToString();
                labelCpm.Text = "Safe";
                toolStripStatusLabel.Text = "Session started and running at " + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " local time.";

                if (Properties.Settings.Default.CalcMethod == "S")
                {
                    AbsorbedValueLabel.Text = "0.0000 µSv";
                }
                else if (Properties.Settings.Default.CalcMethod == "R")
                {
                    AbsorbedValueLabel.Text = "0.0000 µR";
                }
                else
                {
                    AbsorbedValueLabel.Text = "0.0000 µSv";
                }
                logBuffer.Clear();
                perfChart1.Clear();
                listBox1.Items.Clear();
                timer30Sec.Enabled = true;
                timer30Sec.Interval = 30000;
                timer30Sec.Start();
                lock (oneMinuteCMPList)
                {
                    oneMinuteCMPList.Clear();
                }
                startLogButton.Text = "Stop Logging";
                conversionFactorSaveButton.Enabled = false;
                conversionFactorLabel.Enabled = false;
                settingsToolStripMenuItem1.Enabled = false;
                radMonSettingsToolStripMenuItem.Enabled = false;
                fTPUploadSettingsToolStripMenuItem.Enabled = false;
                SaveLogToFileCheckbox.Enabled = false;
                checkBoxConRadMon.Enabled = false;
                checkBoxFtpUpload.Enabled = false;

                perfChart1.TimerMode = SpPerfChart.TimerMode.Simple;
                var stopBitsString = "";

                switch (Properties.Settings.Default.StopBit)
                {
                    case 0:
                        {
                            stopBitsString = "One";
                        }
                        break;
                    case 1:
                        {
                            stopBitsString = "OnePointFive";
                        }
                        break;
                    default:
                        stopBitsString = "Two";
                        break;
                }

                var stopBits = (StopBits)Enum.Parse(typeof(StopBits), stopBitsString);
                var port = Properties.Settings.Default.PortString;
                var parity = (Parity)Enum.Parse(typeof(Parity), Properties.Settings.Default.ParityString);
                var speed = int.Parse(Properties.Settings.Default.SpeedString);
                var dataBits = int.Parse(Properties.Settings.Default.DataBitsString);

                comPort = new SerialPort(port, speed, parity, dataBits, stopBits);
                comPort.DataReceived += comPort_DataReceived;

                if (connectToRadMon == true)
                {
                    if (Properties.Settings.Default.RadMonUserName != "")
                    {
                        if (Properties.Settings.Default.RadMonUserPassword != "")
                        {
                            labelTimeLeft.Text = "Time left untill next upload: " + Convert.ToString(SecondsLeft);
                            toolStripStatusLabelUploaded.Text = "Waiting for first 60 seconds average to upload.";
                            timerUpload.Enabled = true;
                            timerUpload.Interval = 60000;
                            timerUpload.Start();
                            timerOneSec.Enabled = true;
                            timerOneSec.Interval = 1000;
                            timerOneSec.Start();
                        }
                        else
                        {
                            MessageBox.Show("You did not provide your RadMon password.");

                            if (timer30Sec.Enabled == true)
                            {
                                timer30Sec.Stop();
                                timer30Sec.Enabled = false;
                            }
                            else { }

                            comPort.Close();
                            labelCpm.ForeColor = Color.Black;
                            colorProgressBar1.BarColor = Color.DarkGreen;
                            startLogButton.Text = "Start Logging";
                            conversionFactorSaveButton.Enabled = true;
                            conversionFactorLabel.Enabled = true;
                            settingsToolStripMenuItem1.Enabled = true;
                            radMonSettingsToolStripMenuItem.Enabled = true;
                            fTPUploadSettingsToolStripMenuItem.Enabled = true;
                            SaveLogToFileCheckbox.Enabled = true;
                            checkBoxConRadMon.Enabled = true;
                            checkBoxFtpUpload.Enabled = true;

                            if (OneMinuteTimer.Enabled == true)
                            {
                                OneMinuteTimer.Stop();
                                OneMinuteTimer.Enabled = false;
                            }
                            else { }

                            if (FiveMinuteTimer.Enabled == true)
                            {
                                FiveMinuteTimer.Stop();
                                FiveMinuteTimer.Enabled = false;
                            }

                            perfChart1.TimerMode = SpPerfChart.TimerMode.Disabled;
                            colorProgressBar1.Minimum = 0;
                            colorProgressBar1.Maximum = 100;
                            colorProgressBar1.Step = 1;
                            colorProgressBar1.Value = 0;
                            labelIndiMax.Text = "Indicator maximum value: " + colorProgressBar1.Maximum.ToString();
                            labelCpm.Text = "Off";
                            toolStripStatusLabel.Text = "Session stopped";
                            currentRadiationLevelLabel.Text = "0.0000 µSv/h";
                            toolStripStatusLabelUploaded.Text = "Not connected..";
                            timerOneSec.Stop();
                            timerOneSec.Enabled = false;
                            SecondsLeft = 60;
                            labelTimeLeft.Text = "Time left untill next upload: Disabled";
                            timerUpload.Stop();
                            timerUpload.Enabled = false;
                        }
                    }
                    else
                    {
                        MessageBox.Show("You did not provide your RadMon username.");

                        if (timer30Sec.Enabled == true)
                        {
                            timer30Sec.Stop();
                            timer30Sec.Enabled = false;
                        }
                        else { }

                        comPort.Close();
                        labelCpm.ForeColor = Color.Black;
                        colorProgressBar1.BarColor = Color.DarkGreen;
                        startLogButton.Text = "Start Logging";
                        conversionFactorSaveButton.Enabled = true;
                        conversionFactorLabel.Enabled = true;
                        settingsToolStripMenuItem1.Enabled = true;
                        radMonSettingsToolStripMenuItem.Enabled = true;
                        fTPUploadSettingsToolStripMenuItem.Enabled = true;
                        SaveLogToFileCheckbox.Enabled = true;
                        checkBoxConRadMon.Enabled = true;
                        checkBoxFtpUpload.Enabled = true;

                        if (OneMinuteTimer.Enabled == true)
                        {
                            OneMinuteTimer.Stop();
                            OneMinuteTimer.Enabled = false;
                        }
                        else { }

                        if (FiveMinuteTimer.Enabled == true)
                        {
                            FiveMinuteTimer.Stop();
                            FiveMinuteTimer.Enabled = false;
                        }

                        perfChart1.TimerMode = SpPerfChart.TimerMode.Disabled;
                        colorProgressBar1.Minimum = 0;
                        colorProgressBar1.Maximum = 100;
                        colorProgressBar1.Step = 1;
                        colorProgressBar1.Value = 0;
                        labelIndiMax.Text = "Indicator maximum value: " + colorProgressBar1.Maximum.ToString();
                        labelCpm.Text = "Off";
                        toolStripStatusLabel.Text = "Session stopped";
                        currentRadiationLevelLabel.Text = "0.0000 µSv/h";
                        toolStripStatusLabelUploaded.Text = "Not connected..";
                        timerOneSec.Stop();
                        timerOneSec.Enabled = false;
                        SecondsLeft = 60;
                        labelTimeLeft.Text = "Time left untill next upload: Disabled";
                        timerUpload.Stop();
                        timerUpload.Enabled = false;
                    }
                }

                try
                {
                    comPort.Open();
                }
                catch (Exception)
                {
                    labelCpm.ForeColor = Color.Black;
                    colorProgressBar1.BarColor = Color.DarkGreen;
                    startLogButton.Text = "Start Logging";
                    MessageBox.Show("Port is busy");

                    if (timer30Sec.Enabled == true)
                    {
                        timer30Sec.Stop();
                        timer30Sec.Enabled = false;
                    }
                    else { }

                    if (Properties.Settings.Default.LoggerMode == 3)
                    {
                        comPort.Write("<HEARTBEAT0>>");
                    }
                    else { }

                    comPort.Close();
                    conversionFactorSaveButton.Enabled = true;
                    conversionFactorLabel.Enabled = true;
                    settingsToolStripMenuItem1.Enabled = true;
                    radMonSettingsToolStripMenuItem.Enabled = true;
                    fTPUploadSettingsToolStripMenuItem.Enabled = true;
                    SaveLogToFileCheckbox.Enabled = true;
                    checkBoxConRadMon.Enabled = true;
                    checkBoxFtpUpload.Enabled = true;

                    perfChart1.TimerMode = SpPerfChart.TimerMode.Disabled;
                    labelCpm.Text = "Off";
                    toolStripStatusLabel.Text = "Session stopped";
                    toolStripStatusLabelUploaded.Text = "Not connected..";
                    timerOneSec.Stop();
                    timerOneSec.Enabled = false;
                    SecondsLeft = 60;
                    labelTimeLeft.Text = "Time left untill next upload: Disabled";
                    labelFTPTimeLeft.Text = "Time left untill next FTP upload: Disabled";
                    timerUpload.Stop();
                    timerUpload.Enabled = false;
                }

                if (comPort.IsOpen)
                {
                    if (checkBoxConRadMon.Checked == false)
                    {
                        OneMinuteTimer.Enabled = true;
                        OneMinuteTimer.Interval = 60000;
                        OneMinuteTimer.Start();
                    }
                    else { }

                    if (Properties.Settings.Default.LoggerMode == 3)
                    {
                        comPort.Write("<HEARTBEAT1>>");
                    }
                    else { }

                    if (checkBoxFtpUpload.Checked == true)
                    {
                        FiveMinuteTimer.Enabled = true;
                        FiveMinuteTimer.Interval = 300000;
                        FiveMinuteTimer.Start();
                        labelFTPTimeLeft.Text = "Time left untill next upload: " + Convert.ToString(SecondsLeft);
                    }
                }
            }
            else if (startLogButton.Text == "Stop Logging")
            {
                if (timer30Sec.Enabled == true)
                {
                    timer30Sec.Stop();
                    timer30Sec.Enabled = false;
                }
                else { }

                if (alarmOn == true)
                {
                    player.Stop();
                }

                if (ledBulb1.Color != Color.Green)
                {
                    ledBulb1.Color = Color.Green;
                }
                if (ledBulb1.On == true)
                {
                    ledBulb1.On = false;
                }

                if (Properties.Settings.Default.LoggerMode == 3)
                {
                    comPort.Write("<HEARTBEAT0>>");
                }
                else { }

                comPort.Close();
                labelCpm.ForeColor = Color.Black;
                colorProgressBar1.BarColor = Color.DarkGreen;
                startLogButton.Text = "Start Logging";
                conversionFactorSaveButton.Enabled = true;
                conversionFactorLabel.Enabled = true;
                settingsToolStripMenuItem1.Enabled = true;
                radMonSettingsToolStripMenuItem.Enabled = true;
                fTPUploadSettingsToolStripMenuItem.Enabled = true;
                SaveLogToFileCheckbox.Enabled = true;
                checkBoxConRadMon.Enabled = true;
                checkBoxFtpUpload.Enabled = true;

                if (OneMinuteTimer.Enabled == true)
                {
                    OneMinuteTimer.Stop();
                    OneMinuteTimer.Enabled = false;
                }
                else { }

                if (FiveMinuteTimer.Enabled == true)
                {
                    FiveMinuteTimer.Stop();
                    FiveMinuteTimer.Enabled = false;
                }

                perfChart1.TimerMode = SpPerfChart.TimerMode.Disabled;
                colorProgressBar1.Minimum = 0;
                colorProgressBar1.Maximum = 100;
                colorProgressBar1.Step = 1;
                colorProgressBar1.Value = 0;
                labelIndiMax.Text = "Indicator maximum value: " + colorProgressBar1.Maximum.ToString();
                labelCpm.Text = "Off";
                toolStripStatusLabel.Text = "Session stopped";
                currentRadiationLevelLabel.Text = "0.0000 µSv/h";
                toolStripStatusLabelUploaded.Text = "Not connected..";
                timerOneSec.Stop();
                timerOneSec.Enabled = false;
                SecondsLeft = 60;
                labelTimeLeft.Text = "Time left untill next upload: Disabled";
                labelFTPTimeLeft.Text = "Time left untill next FTP upload: Disabled";
                timerUpload.Stop();
                timerUpload.Enabled = false;
            }
            else { }
        }
        #endregion

        #region *** Data receive functions ***
        private void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            switch (Properties.Settings.Default.LoggerMode)
            {
                case 1:
                    Thread.Sleep(500);

                    case1 = new Thread(new ThreadStart(_case1));
                    case1.Start();

                    // Update data for live graph
                    perfChart1.AddValue(cpmParsedInt);

                    // Maximum value switches
                    if (cpmParsedInt < 100)
                    {
                        colorProgressBar1.Maximum = 100;
                        colorProgressBar2.Maximum = 100;
                    }
                    else if (cpmParsedInt < 1000)
                    {
                        colorProgressBar1.Maximum = 1000;
                        colorProgressBar2.Maximum = 1000;
                    }
                    else if (cpmParsedInt < 5000)
                    {
                        colorProgressBar1.Maximum = 5000;
                        colorProgressBar2.Maximum = 5000;
                    }
                    else if (cpmParsedInt < 10000)
                    {
                        colorProgressBar1.Maximum = 10000;
                        colorProgressBar2.Maximum = 10000;
                    }
                    else if (cpmParsedInt < 15000)
                    {
                        colorProgressBar1.Maximum = 15000;
                        colorProgressBar2.Maximum = 15000;
                    }
                    else if (cpmParsedInt < 100000)
                    {
                        colorProgressBar1.Maximum = 100000;
                        colorProgressBar2.Maximum = 100000;
                    }
                    else
                    {
                        colorProgressBar1.Maximum = 10000000;
                        colorProgressBar2.Maximum = 10000000;
                    }

                    // Color change on CPM bar
                    if (cpmParsedInt <= Properties.Settings.Default.WarningThreshold)
                    {
                        labelCpm.ForeColor = Color.DarkGreen;
                        labelCpm.Text = "Safe";
                        colorProgressBar1.BarColor = Color.DarkGreen;
                    }
                    else if (cpmParsedInt <= Properties.Settings.Default.AlertThreshold)
                    {
                        labelCpm.ForeColor = Color.Orange;
                        labelCpm.Text = "Warning";
                        colorProgressBar1.BarColor = Color.Orange;
                    }
                    else
                    {
                        labelCpm.ForeColor = Color.Red;
                        labelCpm.Text = "Alarm!";
                        colorProgressBar1.BarColor = Color.Red;
                    }

                    // Starting Invokes
                    BeginInvoke(new MethodInvoker(() => listBox1.Items.Add(itemToAdd)));
                    BeginInvoke(new MethodInvoker(() => listBox1.TopIndex = listBox1.Items.Count - 1));
                    if (Properties.Settings.Default.CalcMethod == "S")
                    {
                        BeginInvoke(new MethodInvoker(() => currentRadiationLevelLabel.Text = Convert.ToString(cpmParsedInt * confRateConf) + " µSv/h"));
                    }
                    else if (Properties.Settings.Default.CalcMethod == "R")
                    {
                        BeginInvoke(new MethodInvoker(() => currentRadiationLevelLabel.Text = Convert.ToString((cpmParsedInt * confRateConf) * 0.00010718499998148) + " µR/h"));
                    }
                    BeginInvoke(new MethodInvoker(() => colorProgressBar1.Value = cpmParsedInt));
                    if (checkBoxConRadMon.Checked == false)
                    {
                        BeginInvoke(new MethodInvoker(() => colorProgressBar2.Value = cpmParsedInt));
                    }

                    // Add to log file
                    if (saveToLogBool == true)
                    {
                        appendToLog(itemToAdd.ToString());
                    }
                    else { }

                    // Check the alarm
                    checkAlarm(cpmParsedInt);
                    lock (oneMinuteCMPList)
                    {
                        oneMinuteCMPList.Add(cpmParsedInt);
                    }
                    break;

                case 2:
                    Thread.Sleep(500);
                    cpmParsedInt++;
                    break;

                case 3:
                    Thread.Sleep(500);

                    case3 = new Thread(new ThreadStart(_case3));
                    case3.Start();

                    // Update data for live graph
                    perfChart1.AddValue(cpmParsedInt);

                    // Maximum value switches
                    if (cpmParsedInt < 100)
                    {
                        colorProgressBar1.Maximum = 100;
                    }
                    else if (cpmParsedInt < 1000)
                    {
                        colorProgressBar1.Maximum = 1000;
                    }
                    else if (cpmParsedInt < 5000)
                    {
                        colorProgressBar1.Maximum = 5000;
                    }
                    else if (cpmParsedInt < 10000)
                    {
                        colorProgressBar1.Maximum = 10000;
                    }
                    else if (cpmParsedInt < 15000)
                    {
                        colorProgressBar1.Maximum = 15000;
                    }
                    else
                    {
                        colorProgressBar1.Maximum = 100000;
                    }

                    // Color change on CPM bar
                    if (cpmParsedInt <= Properties.Settings.Default.WarningThreshold)
                    {
                        labelCpm.ForeColor = Color.DarkGreen;
                        labelCpm.Text = "Safe";
                        colorProgressBar1.BarColor = Color.DarkGreen;
                    }
                    else if (cpmParsedInt <= Properties.Settings.Default.AlertThreshold)
                    {
                        labelCpm.ForeColor = Color.Orange;
                        labelCpm.Text = "Warning";
                        colorProgressBar1.BarColor = Color.Orange;
                    }
                    else
                    {
                        labelCpm.ForeColor = Color.Red;
                        labelCpm.Text = "Alarm!";
                        colorProgressBar1.BarColor = Color.Red;
                    }

                    // Starting Invokes
                    BeginInvoke(new MethodInvoker(() => listBox1.Items.Add(itemToAdd)));
                    BeginInvoke(new MethodInvoker(() => listBox1.TopIndex = listBox1.Items.Count - 1));
                    if (Properties.Settings.Default.CalcMethod == "S")
                    {
                        BeginInvoke(new MethodInvoker(() => currentRadiationLevelLabel.Text = Convert.ToString(cpmParsedInt * confRateConf) + " µSv/h"));
                    }
                    else if (Properties.Settings.Default.CalcMethod == "R")
                    {
                        BeginInvoke(new MethodInvoker(() => currentRadiationLevelLabel.Text = Convert.ToString((cpmParsedInt * confRateConf) * 0.00010718499998148) + " µR/h"));
                    }
                    BeginInvoke(new MethodInvoker(() => colorProgressBar1.Value = cpmParsedInt));
                    if (checkBoxConRadMon.Checked == false)
                    {
                        BeginInvoke(new MethodInvoker(() => colorProgressBar2.Value = cpmParsedInt));
                    }

                    // Add to log file
                    if (saveToLogBool == true)
                    {
                        appendToLog(itemToAdd.ToString());
                    }
                    else { }

                    // Check the alarm
                    checkAlarm(cpmParsedInt);
                    lock (oneMinuteCMPList)
                    {
                        oneMinuteCMPList.Add(cpmParsedInt);
                    }
                    break;

                default:
                    break;
            }
        }
        #endregion

        #region *** Alarm checking event ***
        private void checkAlarm(int cpm)
        {
            if (cpm >= Properties.Settings.Default.AlertThreshold)
            {
                if (alarmOn == true)
                {
                    player.Stop();
                }
                //Invoke(new MethodInvoker(() => FlashingTimer.Enabled = true));
                //Invoke(new MethodInvoker(() => FlashingStopTimer.Enabled = true));
                Invoke(new MethodInvoker(() => TrayIcon.ShowBalloonTip(100, "Radiation Alert", "Current CPM level = " + cpm.ToString(CultureInfo.InvariantCulture), ToolTipIcon.Error)));
                //led1.ColorOff = Color.Red;
                //led1.Flash = true;
                if (ledBulb1.Color != Color.Red)
                {
                    ledBulb1.Color = Color.Red;
                }
                if (ledBulb1.On == false)
                {
                    ledBulb1.On = true;
                }
                if (alarmOn == true)
                {
                    player.PlayLooping();
                }
            }
            else if (cpm >= Properties.Settings.Default.WarningThreshold)
            {
                player.Stop();
                //Invoke(new MethodInvoker(() => FlashingTimer.Enabled = true));
                //Invoke(new MethodInvoker(() => FlashingStopTimer.Enabled = true));
                Invoke(new MethodInvoker(() => TrayIcon.ShowBalloonTip(100, "Radiation Warning", "Current CPM level = " + cpm.ToString(CultureInfo.InvariantCulture), ToolTipIcon.Warning)));
                //led1.ColorOff = Color.Orange;
                //led1.Flash = true;
                if (ledBulb1.Color != Color.Orange)
                {
                    ledBulb1.Color = Color.Orange;
                }
                if (ledBulb1.On == false)
                {
                    ledBulb1.On = true;
                }
            }
            else
            {
                //led1.Flash = false;
                if (alarmOn == true)
                {
                    player.Stop();
                }
                if (ledBulb1.Color != Color.Green)
                {
                    ledBulb1.Color = Color.Green;
                }
                if (ledBulb1.On == true)
                {
                    ledBulb1.On = false;
                }
            }
        }
        #endregion

        #region *** Append data into the data logging file ***
        private void appendToLog(string stringToAppendToLog)
        {
            if (logBuffer.Count > 0)
            {
                try
                {
                    var log = new StreamWriter(Path.GetFullPath(logFilePath), true);
                    foreach (var logEntry in logBuffer)
                    {
                        log.WriteLine(logEntry);
                    }
                    log.Close();
                    logBuffer.Clear();
                }
                catch (Exception) { }
            }
            else { }

            try
            {
                var log = new StreamWriter(Path.GetFullPath(logFilePath), true);
                log.WriteLine(stringToAppendToLog.Replace(' ', ',').Replace(",CPM", ""));
                log.Close();
            }
            catch (IOException)
            {
                logBuffer.Add(stringToAppendToLog.Replace(' ', ',').Replace(",CPM", ""));
            }

        }
        #endregion

        #region *** Toolstrip menu button click events ***
        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var settingsForm = new ConnectionSettingsForm();
            settingsForm.ShowDialog();
        }

        private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var aboutForm = new About_Radiation_Logger();
            aboutForm.ShowDialog();
        }

        private void emailSupportradiohobbystorecomToolStripMenuItem_Click(object sender, EventArgs e)
        {
            const string emailSupport = "mailto:thibmorozier@live.nl";
            Process.Start(emailSupport);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            close = true;
            CloseProgram();
        }

        private void logsFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start(Application.StartupPath + "/Logs/");
        }

        private void radMonSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var radMonSettingsForm = new RadMon_Connect();
            radMonSettingsForm.ShowDialog();
        }

        private void graphsFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start(Application.StartupPath + "/ChartImages/");
        }

        private void fTPUploadSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var ftpUploadSettingsForm = new FTP_Upload_Settings();
            ftpUploadSettingsForm.ShowDialog();
        }

        private void darkToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.colorSetting = "Dark";
            Properties.Settings.Default.Save();
            darkToolStripMenuItem.Text = "\u2714 Dark";
            lightToolStripMenuItem.Text = "Light";
            colorDark();
        }

        private void lightToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.colorSetting = "Light";
            Properties.Settings.Default.Save();
            darkToolStripMenuItem.Text = "Dark";
            lightToolStripMenuItem.Text = "\u2714 Light";
            colorLight();
        }

        private void exportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.Save();
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
            config.SaveAs(settingsFilePath);
            Application.DoEvents();
        }

        private void importToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!File.Exists(settingsFilePath))
            {
                MessageBox.Show("Error" + Environment.NewLine + "File not found!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                var appSettings = Properties.Settings.Default;
                try
                {
                    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
                    // returns "MyApplication.Properties.Settings";
                    string appSettingsXmlName = Properties.Settings.Default.Context["GroupName"].ToString();
                    // Open settings file as XML
                    var import = XDocument.Load(settingsFilePath);
                    // Get the whole XML inside the settings node
                    var settings = import.XPathSelectElements("//" + appSettingsXmlName);

                    config.GetSectionGroup("userSettings").Sections[appSettingsXmlName].SectionInformation.SetRawXml(settings.Single().ToString());
                    config.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection("userSettings");

                    Application.DoEvents();
                    appSettings.Reload();
                }
                catch (Exception Ex)
                { // Should make this more specific
                    // Could not import settings.
                    appSettings.Reload(); // from last set saved, not defaults
                    MessageBox.Show("Error importing the configuration." + Environment.NewLine + Ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void useΜSvToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.CalcMethod == "R")
            {
                Properties.Settings.Default.CalcMethod = "S";
                Properties.Settings.Default.Save();
                useΜSvToolStripMenuItem.Text = "\u2714 Use µSv";
                useΜRToolStripMenuItem.Text = "Use µR";
                currentRadiationLevelLabel.Text = "0.0000 µSv/h";
                AbsorbedValueLabel.Text = "0.0000 µSv";
            }
            else { }
        }

        private void useΜRToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.CalcMethod == "S")
            {
                Properties.Settings.Default.CalcMethod = "R";
                Properties.Settings.Default.Save();
                useΜSvToolStripMenuItem.Text = "Use µSv";
                useΜRToolStripMenuItem.Text = "\u2714 Use µR";
                currentRadiationLevelLabel.Text = "0.0000 µR/h";
                AbsorbedValueLabel.Text = "0.0000 µR";
            }
            else { }
        }

        private void alarmOnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (alarmOn != true)
            {
                alarmOnToolStripMenuItem.Text = "\u2714 Alarm on";
                alarmOn = true;
                Properties.Settings.Default.alarmOn = alarmOn;
                Properties.Settings.Default.Save();
            }
            else
            {
                alarmOnToolStripMenuItem.Text = "Alarm on";
                alarmOn = false;
                Properties.Settings.Default.alarmOn = alarmOn;
                Properties.Settings.Default.Save();
            }
        }
        #endregion

        #region *** Tray icon events ***
        private void TrayIcon_DoubleClick(object sender, EventArgs e)
        {
            Show();
        }

        private void TrayIcon_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {

            }
            else { }
        }

        private void OpenContextMenuItem1_Click(object sender, EventArgs e)
        {
            Show();
        }

        private void ExitContextMenuItem1_Click(object sender, EventArgs e)
        {
            close = true;
            CloseProgram();
        }
        #endregion

        #region *** Form closing events ***
        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (close || e.CloseReason == CloseReason.WindowsShutDown)
            {
                CloseProgram();
            }
            else
            {
                e.Cancel = true;
                Hide();
            }
        }

        private void CloseProgram()
        {
            try
            {
                comPort.Close();
            }
            catch (Exception) { }
            try
            {
                Application.Exit();
            }
            catch (Exception) { }
            try
            {
                TrayIcon.Dispose();
            }
            catch (Exception) { }

        }
        #endregion

        #region *** Timer events ***
        private void FiveMinuteTimer_Tick(object sender, EventArgs e)
        {
            _ftp = new Thread(new ThreadStart(UploadFileToFTP));
            _ftp.Start();
        }

        private void OneMinuteTimer_Tick(object sender, EventArgs e)
        {
            lock (oneMinuteCMPList)
            {
                try
                {
                    oneMinuteAverage = (int)oneMinuteCMPList.Average() * Properties.Settings.Default.ConversionFactor;
                    absorbed = absorbed + oneMinuteAverage / 60;
                }
                catch (Exception)
                {

                }
            }

            if (Properties.Settings.Default.CalcMethod == "S")
            {
                double absorbedMicroSievert = Math.Round(absorbed, 4, MidpointRounding.AwayFromZero);
                AbsorbedValueLabel.Text = Convert.ToString(absorbedMicroSievert) + " µSv";
            }
            else if (Properties.Settings.Default.CalcMethod == "R")
            {
                double absorbedMicroSievert = Math.Round((absorbed * 0.00010718499998148), 4, MidpointRounding.AwayFromZero);
                AbsorbedValueLabel.Text = Convert.ToString(absorbedMicroSievert) + " µR";
            }

            lock (oneMinuteCMPList)
            {
                oneMinuteCMPList.Clear();
            }

            if (ftpUpload == true)
            {
                try
                {
                    Application.DoEvents();
                }
                catch (Exception Ex)
                {
                    MessageBox.Show("Error uploading chart : " + Ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void timer30Sec_Tick(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.LoggerMode == 2)
            {
                var itemToAdd = new StringBuilder();
                itemToAdd.Append(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
                itemToAdd.Append(" ");
                itemToAdd.Append(Convert.ToString(cpmParsedInt * 2));
                itemToAdd.Append(" CPM");

                // Update data for live graph
                perfChart1.AddValue(cpmParsedInt * 2);

                // Maximum value switches
                if (cpmParsedInt * 2 < 100)
                {
                    colorProgressBar1.Maximum = 100;
                }
                else if (cpmParsedInt * 2 < 1000)
                {
                    colorProgressBar1.Maximum = 1000;
                }
                else if (cpmParsedInt * 2 < 5000)
                {
                    colorProgressBar1.Maximum = 5000;
                }
                else if (cpmParsedInt * 2 < 10000)
                {
                    colorProgressBar1.Maximum = 10000;
                }
                else if (cpmParsedInt * 2 < 15000)
                {
                    colorProgressBar1.Maximum = 15000;
                }
                else
                {
                    colorProgressBar1.Maximum = 100000;
                }

                // Color change on CPM bar
                if (cpmParsedInt * 2 <= Properties.Settings.Default.WarningThreshold)
                {
                    labelCpm.ForeColor = Color.DarkGreen;
                    labelCpm.Text = "Safe";
                    colorProgressBar1.BarColor = Color.DarkGreen;
                }
                else if (cpmParsedInt * 2 <= Properties.Settings.Default.AlertThreshold)
                {
                    labelCpm.ForeColor = Color.Orange;
                    labelCpm.Text = "Warning";
                    colorProgressBar1.BarColor = Color.Orange;
                }
                else
                {
                    labelCpm.ForeColor = Color.Red;
                    labelCpm.Text = "Alarm!";
                    colorProgressBar1.BarColor = Color.Red;
                }

                // Starting Invokes
                listBox1.Items.Add(itemToAdd);
                listBox1.TopIndex = listBox1.Items.Count - 1;
                double confRateConf = Properties.Settings.Default.ConversionFactor;
                if (Properties.Settings.Default.CalcMethod == "S")
                {
                    currentRadiationLevelLabel.Text = Convert.ToString((cpmParsedInt * 2) * confRateConf) + " µSv/h";
                }
                else if (Properties.Settings.Default.CalcMethod == "R")
                {
                    currentRadiationLevelLabel.Text = Convert.ToString(((cpmParsedInt * 2) * confRateConf) * 0.00010718499998148) + " µR/h";
                }
                colorProgressBar1.Value = cpmParsedInt * 2;
                if (checkBoxConRadMon.Checked == false)
                {
                    colorProgressBar2.Value = cpmParsedInt * 2;
                }

                // Add to log file
                if (saveToLogBool == true)
                {
                    appendToLog(itemToAdd.ToString());
                }
                else { }

                // Check the alarm
                checkAlarm(cpmParsedInt * 2);
                lock (oneMinuteCMPList)
                {
                    oneMinuteCMPList.Add(cpmParsedInt * 2);
                }

                cpmParsedInt = 0;
            }
            else if (Properties.Settings.Default.LoggerMode == 3)
            {
                comPort.Write("<GETCPM>>");
            }
            else { }
        }
        #endregion

        #region *** Custom graph button events ***
        private void buttonLineSolid_Click(object sender, EventArgs e)
        {
            perfChart1.PerfChartStyle.ChartLinePen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
            Application.DoEvents();
        }

        private void buttonLineDotted_Click(object sender, EventArgs e)
        {
            perfChart1.PerfChartStyle.ChartLinePen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
            Application.DoEvents();
        }

        private void buttonLineDashed_Click(object sender, EventArgs e)
        {
            perfChart1.PerfChartStyle.ChartLinePen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
            Application.DoEvents();
        }

        private void buttonAvgOn_Click(object sender, EventArgs e)
        {
            perfChart1.PerfChartStyle.AvgLinePen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
            perfChart1.PerfChartStyle.ShowAverageLine = true;
            Application.DoEvents();
        }

        private void buttonAvgOff_Click(object sender, EventArgs e)
        {
            perfChart1.PerfChartStyle.AvgLinePen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
            perfChart1.PerfChartStyle.ShowAverageLine = false;
            Application.DoEvents();
        }

        private void buttonSaveCustomGraph_Click(object sender, EventArgs e)
        {
            try
            {
                using (var png = new Bitmap(perfChart1.Width, perfChart1.Height))
                {
                    perfChart1.DrawToBitmap(png, new Rectangle(0, 0, png.Width, png.Height));
                    png.Save(Application.StartupPath + @"\ChartImages\chart" + DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss", CultureInfo.InvariantCulture) + @".png", System.Drawing.Imaging.ImageFormat.Png);
                    png.Dispose();
                }
                MessageBox.Show("The chart image has been saved to" + Path.GetDirectoryName(Application.ExecutablePath) + @"\ChartImages\");
            }
            catch (Exception Ex)
            {
                MessageBox.Show("Error saving the chart." + Ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region *** Coloring ***
        private void colorDark()
        {
            Application.DoEvents();
            menuStrip1.BackColor = Color.FromArgb(60, 60, 60);
            lightToolStripMenuItem.BackColor = Color.FromArgb(60, 60, 60);
            darkToolStripMenuItem.BackColor = Color.FromArgb(60, 60, 60);
            sendUsAnSupportEmailToolStripMenuItem.BackColor = Color.FromArgb(60, 60, 60);
            aboutToolStripMenuItem1.BackColor = Color.FromArgb(60, 60, 60);
            logsFolderToolStripMenuItem.BackColor = Color.FromArgb(60, 60, 60);
            logsToolStripMenuItem.BackColor = Color.FromArgb(60, 60, 60);
            graphsFolderToolStripMenuItem.BackColor = Color.FromArgb(60, 60, 60);
            graphsToolStripMenuItem.BackColor = Color.FromArgb(60, 60, 60);
            settingsToolStripMenuItem.BackColor = Color.FromArgb(60, 60, 60);
            settingsToolStripMenuItem1.BackColor = Color.FromArgb(60, 60, 60);
            radMonSettingsToolStripMenuItem.BackColor = Color.FromArgb(60, 60, 60);
            fTPUploadSettingsToolStripMenuItem.BackColor = Color.FromArgb(60, 60, 60);
            exitToolStripMenuItem.BackColor = Color.FromArgb(60, 60, 60);
            exitToolStripMenuItem1.BackColor = Color.FromArgb(60, 60, 60);
            exportToolStripMenuItem.BackColor = Color.FromArgb(60, 60, 60);
            importToolStripMenuItem.BackColor = Color.FromArgb(60, 60, 60);
            statusStrip1.BackColor = Color.FromArgb(60, 60, 60);
            listBox1.BackColor = Color.Black;
            listBox1.ForeColor = Color.Maroon;
            groupBox1.ForeColor = Color.Maroon;
            groupBox4.ForeColor = Color.Green;
            groupBox5.ForeColor = Color.Green;
            groupBox6.ForeColor = Color.Maroon;
            groupBox7.ForeColor = Color.Green;
            groupBox8.ForeColor = Color.Maroon;
            label1.ForeColor = Color.Green;
            label2.ForeColor = Color.Green;
            label3.ForeColor = Color.Green;
            labelIndiMax.ForeColor = Color.Maroon;
            labelTimeLeft.ForeColor = Color.Green;
            SaveLogToFileCheckbox.ForeColor = Color.Green;
            checkBoxConRadMon.ForeColor = Color.Green;
            checkBoxFtpUpload.ForeColor = Color.Green;
            AbsorbedValueGroupbox.ForeColor = Color.Maroon;
            AbsorbedValueLabel.ForeColor = Color.Maroon;
            CurrentRadiationLevelGroupbox.ForeColor = Color.Maroon;
            currentRadiationLevelLabel.ForeColor = Color.Maroon;
            tabPage2.BackColor = Color.DimGray;
            tabPage5.BackColor = Color.DimGray;
            this.BackColor = Color.FromArgb(50, 50, 50);
            Application.DoEvents();
        }

        private void colorLight()
        {
            Application.DoEvents();
            menuStrip1.BackColor = Color.FromName("ScrollBar");
            lightToolStripMenuItem.BackColor = Color.FromName("ScrollBar");
            darkToolStripMenuItem.BackColor = Color.FromName("ScrollBar");
            sendUsAnSupportEmailToolStripMenuItem.BackColor = Color.FromName("ScrollBar");
            aboutToolStripMenuItem1.BackColor = Color.FromName("ScrollBar");
            logsFolderToolStripMenuItem.BackColor = Color.FromName("ScrollBar");
            logsToolStripMenuItem.BackColor = Color.FromName("ScrollBar");
            graphsFolderToolStripMenuItem.BackColor = Color.FromName("ScrollBar");
            graphsToolStripMenuItem.BackColor = Color.FromName("ScrollBar");
            settingsToolStripMenuItem.BackColor = Color.FromName("ScrollBar");
            settingsToolStripMenuItem1.BackColor = Color.FromName("ScrollBar");
            radMonSettingsToolStripMenuItem.BackColor = Color.FromName("ScrollBar");
            fTPUploadSettingsToolStripMenuItem.BackColor = Color.FromName("ScrollBar");
            exitToolStripMenuItem.BackColor = Color.FromName("ScrollBar");
            exitToolStripMenuItem1.BackColor = Color.FromName("ScrollBar");
            exportToolStripMenuItem.BackColor = Color.FromName("ScrollBar");
            importToolStripMenuItem.BackColor = Color.FromName("ScrollBar");
            statusStrip1.BackColor = Color.FromName("ScrollBar");
            listBox1.BackColor = Color.FromName("Control");
            listBox1.ForeColor = Color.Black;
            groupBox1.ForeColor = Color.Black;
            groupBox4.ForeColor = Color.Black;
            groupBox5.ForeColor = Color.Black;
            groupBox6.ForeColor = Color.Black;
            groupBox7.ForeColor = Color.Black;
            groupBox8.ForeColor = Color.Black;
            label1.ForeColor = Color.Black;
            label2.ForeColor = Color.Black;
            label3.ForeColor = Color.Black;
            labelIndiMax.ForeColor = Color.Black;
            labelTimeLeft.ForeColor = Color.Black;
            SaveLogToFileCheckbox.ForeColor = Color.Black;
            checkBoxConRadMon.ForeColor = Color.Black;
            checkBoxFtpUpload.ForeColor = Color.Black;
            AbsorbedValueGroupbox.ForeColor = Color.Black;
            AbsorbedValueLabel.ForeColor = Color.Black;
            CurrentRadiationLevelGroupbox.ForeColor = Color.Black;
            currentRadiationLevelLabel.ForeColor = Color.Black;
            tabPage2.BackColor = Color.FromName("Control");
            tabPage5.BackColor = Color.FromName("Control");
            this.BackColor = Color.FromName("Control");
            Application.DoEvents();
        }
        #endregion

        #region *** Threads gathering ***
        private void _radUpload()
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create(
                "http://www.radmon.org/radmon.php?user=" +
                Properties.Settings.Default.RadMonUserName +
                "&password=" + Properties.Settings.Default.RadMonUserPassword +
                "&function=submit&datetime=" + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") +
                "&value=" + intToUpload + "&unit=CPM");
            request.Timeout = 15000;
            Application.DoEvents();

            // Get the response.
            try
            {
                WebResponse response;
                using (response = request.GetResponse()) { }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error submitting value : " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            _rad.Abort();
        }

        private void _case1()
        {
            itemToAdd.Clear();
            try
            {
                cpmReceivedString = comPort.ReadExisting().Trim();
            }
            catch (Exception) { }

            if (!int.TryParse(cpmReceivedString, out cpmParsedInt))
            {
                return;
            }
            else { }

            itemToAdd.Append(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
            itemToAdd.Append(" ");
            itemToAdd.Append(cpmReceivedString);
            itemToAdd.Append(" CPM");

            case1.Abort();
        }

        private void _case3()
        {
            itemToAdd.Clear();
            try
            {
                cpmReceivedString = comPort.ReadExisting().Trim();
            }
            catch (Exception) { }

            if (!int.TryParse(cpmReceivedString, out cpmParsedInt))
            {
                return;
            }
            else { }

            itemToAdd.Append(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
            itemToAdd.Append(" ");
            itemToAdd.Append(cpmReceivedString);
            itemToAdd.Append(" CPM");

            case3.Abort();
        }
        #endregion

    }
}

